<template>
  <div id="tree">

    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <el-checkbox-group
      v-model="checkedCities"
      @change="handleCheckedCitiesChange"
    >
      <el-checkbox v-for="city in cities" :label="city" :key="city">{{
        city
      }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script>

import MultiFieldAdaptWindow from "./PopupWindow";
// const cityOptions = ['人脸卡扣相机', '其他类型'];
export default {
  data() {
    return {
      checkAll: false,
    //   checkedCities: ["人脸卡扣相机"],
    checkedCities: [],
      initBool: false,
      // cities: cityOptions,

      cities: ["人脸卡扣相机", "其他类型"],

      isIndeterminate: true,
      defaultchecked: [1],

      beijing: [
        {
          name: "北京西路与北京路交叉口",
          ip: "172.16.12.23",
          type: "固定枪机1",
          state: "在线",
          position: {
            x: -1642312.5134694357,
            y: 5410103.431854676,
            z: 2942105.546479778,
          },
        },
        {
          name: "阿化修理店门口",
          ip: "172.16.12.22",
          type: "固定枪机2",
          state: "在线",
          position: {
            x: -1642335.9668148402,
            y: 5410073.68998821,
            z: 2942146.013788689,
          },
        },
      ],
      shanghai: [
        {
          name: "瑞安市钢材市场(东新路店)",
          ip: "172.16.12.12",
          type: "固定枪机3",
          state: "在线",
          position: {
            x: -1642349.165646185,
            y: 5410058.839841634,
            z: 2942167.85307159,
          },
        },
        {
          name: "安心大药房(上旺西路店)",
          ip: "172.16.12.25",
          type: "固定枪机4",
          state: "在线",
          position: {
            x: -1642234.6906042907,
            y: 5410203.789605635,
            z: 2941976.755600351,
          },
        },
      ],


    };
  },
  created() {

debugger;
this.load3dtiles();
this.SelectleftClick();
      viewer.selectedEntityChanged.addEventListener(e => {
            this.selectedEntityChanged(e);
        });
  },
  mounted() {

  },

  methods: {

    SelectleftClick(){

// // var viewer = new Cesium.Viewer('cesiumContainer');
debugger;
var handler= new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(function (movement) {
     console.log(movement.position);



// 通过 viewer.scene.camera.pickEllipsoid(movement.position, ellipsoid)获取，可以获取当前点击视线与椭球面相交处的坐标，其中ellipsoid是当前地球使用的椭球对象：viewer.scene.globe.ellipsoid。

//2、世界坐标（Cartesian3）
// 作者：WebGiser
// 链接：https://www.jianshu.com/p/e7e65b448eeb
// 来源：简书
// 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
    //     var position = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
    //  console.log(position);


    //  通过viewer.scene.pickPosition(movement.position)获取，根据窗口坐标，从场景的深度缓冲区中拾取相应的位置，返回笛卡尔坐标。
//3、场景坐标

// var viewer = new Cesium.Viewer('cesiumContainer');

// var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// handler.setInputAction(function (movement) {
//      var position = viewer.scene.pickPosition(movement.position);
//      console.log(position);
// }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


// 4、地标坐标
// 通过viewer.scene.globe.pick(ray, scene)获取，可以获取点击处地球表面的世界坐标，不包括模型、倾斜摄影表面。其中ray=viewer.camera.getPickRay(movement.position)。

// var viewer = new Cesium.Viewer('cesiumContainer');

// var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// handler.setInputAction(function (movement) {
//      var ray=viewer.camera.getPickRay(movement.position);
//      var position = viewer.scene.globe.pick(ray, viewer.scene);
//      console.log(position);
// }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


// 作者：WebGiser
// 链接：https://www.jianshu.com/p/e7e65b448eeb
// 来源：简书
// 著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
 var position = viewer.scene.pickPosition(movement.position);
     console.log(position);

debugger;


let Cartesian3=position;
        if (!Cartesian3 || !Cartesian3.x) {
            throw "Error in parameters";
        }
       let _cartesian3 = new Cesium.Cartesian3(Cartesian3.x, Cartesian3.y, Cartesian3.z);
        let _cartographic = Cesium.Cartographic.fromCartesian(_cartesian3);
        let _lat = Cesium.Math.toDegrees(_cartographic.latitude);
        let _lng = Cesium.Math.toDegrees(_cartographic.longitude);
        let _alt = _cartographic.height;

        console.log(JSON.stringify({lng: _lng, lat: _lat, alt: _alt}));

}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    },


initMonitors(idname,monitors) {
        // let monitors = [
        //     { name: "北京西路与北京路交叉口", ip: "172.16.12.23", type: "固定枪机1", state: "在线", position: { x: -1642312.5134694357, y: 5410103.431854676, z: 2942105.546479778 } },
        //     { name: "阿化修理店门口", ip: "172.16.12.22", type: "固定枪机2", state: "在线", position: { x: -1642335.9668148402, y: 5410073.68998821, z: 2942146.013788689 } },
        //     { name: "瑞安市钢材市场(东新路店)", ip: "172.16.12.12", type: "固定枪机3", state: "在线", position: { x: -1642349.165646185, y: 5410058.839841634, z: 2942167.85307159 } },
        //     { name: "安心大药房(上旺西路店)", ip: "172.16.12.25", type: "固定枪机4", state: "在线", position: { x: -1642234.6906042907, y: 5410203.789605635, z: 2941976.755600351 } },
        // ]

        monitors.forEach(item => {
          viewer.entities.add({
                position: item.position,
                _name:idname,
                name:idname,
                info: item,
                billboard: {
                    // image: 'blueCamera.png',
                    image:require('./blueCamera.png'), 
                    scaleByDistance: new Cesium.NearFarScalar(500, 1, 1200, 0.8),
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM
                }
            })
        })
    },

    initWindow() {
        let point = {
            x: 4172011.3630057382,
            y: 967275.9661719546,
            z: 4726545.152380189
        }
      viewer.entities.add({
            position: point,
            _name:'lablebill',
            name:'lablebill',
            billboard: {
                image: 'blueCamera.png',
                scaleByDistance: new Cesium.NearFarScalar(500, 1, 1200, 0.8),
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM
            }
        })
        let window = new MultiFieldAdaptWindow(viewer, point, "监控信息", ["监控名称", "IP地址", "监控类型", "监控状态"], ["北京西路口隧道入口", "52.19.98.23", "固定枪机", "在线"]);
    },




    selectedEntityChanged(e) {


        var entitys = viewer.entities._entities._array;

     
        if (!e) return;
        if (this.Window1) {
            this.Window1.windowClose();
            this.Window1 = undefined;
        }
        debugger;
        this.Window1 = new MultiFieldAdaptWindow(viewer, e.position._value, "监控信息", ["监控名称", "IP地址", "监控类型", "监控状态"], [e.info.name, e.info.ip, e.info.type, e.info.state]);
    
  debugger;

  let Cartesian3=e.position._value;
        if (!Cartesian3 || !Cartesian3.x) {
            throw "Error in parameters";
        }
     
        let _cartesian3 = new Cesium.Cartesian3(Cartesian3.x, Cartesian3.y, Cartesian3.z);
        let _cartographic = Cesium.Cartographic.fromCartesian(_cartesian3);
        let _lat = Cesium.Math.toDegrees(_cartographic.latitude);
        let _lng = Cesium.Math.toDegrees(_cartographic.longitude);
        let _alt = _cartographic.height;

        console.log(JSON.stringify({lng: _lng, lat: _lat, alt: _alt}));
        // return {lng: _lng, lat: _lat, alt: _alt};
    // Cartesian3ToWGS84(e.position._value);

    },

    // Cartesian3ToWGS84(Cartesian3){
    
 
    // },

    deleteEntity(idName) {

        debugger;
        var entitys = viewer.entities._entities._array;

        for (var i = 0; i < entitys.length; i++) {
            if (entitys[i]._name === idName) {
                debugger;
                console.log("i=" + i);
                console.log(entitys[i]._name);
                console.log(entitys[i]._id);                  
              viewer.entities.remove(entitys[i]);
                i--;
            }
        }
    
    },


    //加载3dtiles数据
    load3dtiles() {

        debugger;
        var tileset = viewer.scene.primitives.add(
            new Cesium.Cesium3DTileset({
                url: "http://116.63.83.180:8080/data-01/zy3dtiles/tileset.json",
            })
        );

        tileset.readyPromise
            .then(tileset => {
                viewer.zoomTo(
                    tileset,
                );
                this.setTilesetHeight(tileset);
            })
            .otherwise(function(error) {
                console.log(error);
            });
    },

    //调整3dtiles的高度位置
    setTilesetHeight(tileset) {
        var cartographic = Cesium.Cartographic.fromCartesian(
            tileset.boundingSphere.center
            // tileset.boundingSphere.center
        );
        debugger;
        var surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
        cartographic.height
        );
        var offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            // -75
            //55
              0
        );
        var translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
        );
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    },


    handleCheckAllChange(val) {
      debugger;
   
      this.checkedCities = val ? this.cities : [];

      this.deleteEntity("beijing", this.beijing);
     this.deleteEntity("shanghai", this.shanghai);
  
      for (var i = 0; i < this.checkedCities.length; i++) {
        if (this.checkedCities[0] == "其他类型") {
          this.initMonitors("beijing", this.beijing);
        } else if (this.checkedCities[0] == "人脸卡扣相机") {
          this.initMonitors("shanghai", this.shanghai);
        }
      }

      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      debugger;
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;

      this.deleteEntity("beijing", this.beijing);
      this.deleteEntity("shanghai", this.shanghai);
     
      for (var i = 0; i < this.checkedCities.length; i++) {
        if (this.checkedCities[i] == "其他类型") {
          this.initMonitors("beijing", this.beijing);
        } else if (this.checkedCities[i] == "人脸卡扣相机") {
          this.initMonitors("shanghai", this.shanghai);
        }
      }


    },

  },
  beforeDestroy() {
 
  },
  destroyed() {
       if (this.Window1) {
            this.Window1.windowClose();
            this.Window1 = undefined;
        }
        viewer.entities.removeAll();
 
 
  },
  
};
</script>
